package com.ctk.wifi.a.net;

import android.annotation.SuppressLint;
import java.io.ByteArrayOutputStream;
import java.io.IOException;



@SuppressLint("DefaultLocale")
public class CommunicationProtocols {
	private byte[] mBuffer = null;
	private StringBuffer mHexBuffer = null;
	private StringBuffer mDebug = null;
	
	/**
	 * 通信协议类库的入口参数指定统一形式是原始16进制数据流byte[]
	 * 
	 * @param src byte[] the hex value
	 *
	 */
	public CommunicationProtocols(byte[] mBuffer) {
		this.mBuffer = mBuffer;
		mHexBuffer = new StringBuffer();	//最终组包数据的字符串形式的16进制数
		mDebug = new StringBuffer();	//调试信息变量
	}

	/**
	 * build data packet base on communication protocols
	 * @return 
	 * 
	 * @throws Exception
	 */
	public String buildDataPacket() throws Exception {
		short payloadL =  (short) mBuffer.length;
		int vHeadLength = payloadL & 0xFFFF;
        String hvHeadLength = Integer.toHexString(vHeadLength);
		if (hvHeadLength.length() == 1) {   
			hvHeadLength = "000" + hvHeadLength;   
		}
		else if (hvHeadLength.length() == 2) {
			hvHeadLength = "00" + hvHeadLength;
		}
		else if (hvHeadLength.length() == 3) {
			hvHeadLength = "0" + hvHeadLength;
		}		
		String hvPayload = bytesToHexString(mBuffer);
		mHexBuffer.append("4441").append(hvHeadLength).append(hvPayload.toUpperCase());
		
		//调试信息部分
		mDebug.setLength(0);
		mDebug.append("Received:\n");
		mDebug.append("HeadLength: ").append(Integer.toString(vHeadLength)).append("\n");
		mDebug.append("HeadType: ").append("Data").append("\n");
		mDebug.append("Payload: ").append("\n");
		mDebug.append(new String(mBuffer)).append("\n");
		mDebug.append(mHexBuffer);
		
		return new String(hexStringToBytes(mHexBuffer.toString()));
	}
	
	/**
	 * parse data packet base on communication protocols
	 * 
	 * @throws Exception
	 */	
	public void parseDataPacket() throws Exception {
		
	}
	
	/**
	 * build command packet base on communication protocols
	 * 
	 * @throws Exception
	 */
	public void buildCommandPacket() throws Exception {
		short payloadL =  (short) mBuffer.length;
		int vHeadLength = payloadL & 0xFFFF;
        String hvHeadLength = Integer.toHexString(vHeadLength);
		if (hvHeadLength.length() == 1) {   
			hvHeadLength = '0' + hvHeadLength;   
		}
		String hvPayload = bytesToHexString(mBuffer);
		mHexBuffer.append("4441").append(hvHeadLength).append(hvPayload.toUpperCase());

	}
	
	/**
	 * parse command packet base on communication protocols
	 * 
	 * @throws Exception
	 */	
	public void parseCommandPacket() throws Exception {
		
	}
	
	/**
	 * output final hex string packet
	 * 
	 * @throws Exception
	 */	
	public void output() throws Exception {
		UDPSocketActivity.content = new String(mDebug.toString()) + "\n";
		UDPSocketActivity.mHandler.sendMessage(UDPSocketActivity.mHandler.obtainMessage());
	}
	
	/**
	 * 将不同的byte[]原始数据流打包成一个原始数据流
	 * @param byte[] the hex value  
	 * @return byte[] the hex value
	 */
	public static byte[] packByteArray(byte[]... agrs) {
		ByteArrayOutputStream bout = new ByteArrayOutputStream();
		for(byte[] b:agrs){
			if(b!=null){
				try {
					bout.write(b);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			continue;
		}
		byte[] buff = bout.toByteArray();
		return buff;
	}	
	
	/**
	 * Convert byte[] to hex string.
	 * 原始16进制数byte[]转换成字符串形式的16进制数（数据流）。  
	 * @param src byte[] the hex value
	 * @return  hex string  
	 */     
	public static String bytesToHexString(byte[] src){  
		StringBuilder stringBuilder = new StringBuilder("");  
	    if (src == null || src.length <= 0) {  
	        return null;  
	    }
	    for (int i = 0; i < src.length; i++) {  
	        int v = src[i] & 0xFF;  
	        String hv = Integer.toHexString(v);  
	        if (hv.length() < 2) {  
	            stringBuilder.append(0);  
	        }  
	        stringBuilder.append(hv);  
	    }  
	    return stringBuilder.toString();  
	}
	
	/** 
	 * Convert hex string to byte[] 
	 * 字符串形式的16进制数转换成原始16进制数byte[]（数据流）。  
	 * @param hexString the hex string 
	 * @return byte[] the hex value
	 */  
	public static byte[] hexStringToBytes(String hexString) {  
	    if (hexString == null || hexString.equals("")) {  
	        return null;  
	    }  
	    hexString = hexString.toUpperCase().trim();  
	    int length = hexString.length() / 2;  
	    char[] hexChars = hexString.toCharArray();  
	    byte[] d = new byte[length];  
	    for (int i = 0; i < length; i++) {  
	        int pos = i * 2;  
	        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
	    }  
	    return d;  
	}
	
	/** 
	 * Convert char to byte
	 * 字符串形式的16进制数转换成原始16进制数（单字节）
	 * @param c char 
	 * @return byte the hex value
	 */  
	 private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	}
	 
	 
	 /** 
	  * Convert byte[] to hex string.
	  * 将指定原始16进制数byte[]以字符串形式的16进制数打印到控制台  
	  * @param b the hex value 
	  * 
	  */  
	public static void printHexString(byte[] b) {    
	   for (int i = 0; i < b.length; i++) {   
	     String hex = Integer.toHexString(b[i] & 0xFF);   
	     if (hex.length() == 1) {   
	       hex = '0' + hex;   
	     }   
	     System.out.print(hex.toUpperCase() );   
	   }   
	}  
	

}